package com.york.tinyrpc.protoss.springboot.startert.bootstrap;

import com.york.tinyrpc.protoss.TinyRpcApplication;
import com.york.tinyrpc.protoss.config.TinyRpcConfig;
import com.york.tinyrpc.protoss.server.tcp.VertxTcpServer;
import com.york.tinyrpc.protoss.springboot.startert.annotation.EnableTinyRpc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * TinyRpc 框架启动
 */
public class TinyRpcInitBootstrap implements ImportBeanDefinitionRegistrar {

    private static final Logger log = LoggerFactory.getLogger(TinyRpcInitBootstrap.class);


    /**
     * Spring 初始化时执行，初始化 RPC 框架
     *
     * @param importingClassMetadata
     * @param registry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        // 获取 EnableRpc 注解的属性值
        boolean needServer = (boolean) importingClassMetadata.getAnnotationAttributes(EnableTinyRpc.class.getName())
                .get("needServer");

        // TinyRpcApplication 框架初始化（配置和注册中心）
        TinyRpcApplication.init();

        // 全局配置
        final TinyRpcConfig rpcConfig = TinyRpcApplication.getRpcConfig();

        // 启动服务器
        if (needServer) {
            VertxTcpServer vertxTcpServer = new VertxTcpServer();
            vertxTcpServer.doStart(rpcConfig.getServerPort());
        } else {
            log.info("不启动 server");
        }

    }
}
